#include "errno.h"
#include "cf_std.h"
#include "cf_session.h"
#include "lcf_log.h"
#include "cf_errno.h"

int CFSessionInit(CFSession* session, const char *sPh, time_t expireSeconds)
{
    memset(session, 0, sizeof(CFSession));
    if(sPh)
        strncpy(session->sessionPhrase, sPh, CF_SESSION_PHRASE_LEN+1);
    else
        strcpy(session->sessionPhrase, "");
    session->sessionPhrase[CF_SESSION_PHRASE_LEN] = '\0';
    session->authTime = time(NULL);
    session->expireSeconds = expireSeconds;
    return 0;
}

CFSession* CFSessionNew(const char sPh[CF_SESSION_PHRASE_LEN], time_t expireSeconds)
{
    CFSession* ret = malloc(sizeof(CFSession));
    if(!ret){
        LCF_ERR(strerror(errno));
        return NULL;
    }
    if(CFSessionInit(ret, sPh, expireSeconds)){
        LCF_DBG("\n");
        return NULL;
    }
    return ret;
}

BOOL CFSessionTimeout(CFSession* session)
{
    time_t now;

    now = time(NULL);
    if((time_t)now < (time_t)session->authTime ||
            ((time_t)now - (time_t)session->authTime) > session->expireSeconds){
        errno = ETIMEDOUT;
        return TRUE;
    }
    return FALSE;
}

int CFSessionAuth(CFSession* session, const char phrase[CF_SESSION_PHRASE_LEN+1])
{
    time_t now;

    now = time(NULL);
    if((time_t)now < (time_t)session->authTime ||
            ((time_t)now - (time_t)session->authTime) > session->expireSeconds){
        errno = ETIMEDOUT;
        return CF_E_AUTH;
    }
    if(!strncmp(session->sessionPhrase, phrase, CF_SESSION_PHRASE_LEN)){
        session->authTime = now;
        return 0;
    }else{
        return CF_E_AUTH;
    }
}

int CFSessionFree(CFSession* toFree)
{
    free(toFree);
    return 0;
}